package com.fanketly.musicdiary.ui.screen

import ando.file.core.FileUri
import android.content.ContentValues
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fanketly.musicdiary.data.TAG
import com.fanketly.musicdiary.domain.DiaryUiState
import com.fanketly.musicdiary.domain.DiaryViewModel
import com.fanketly.musicdiary.domain.MusicViewModel
import com.fanketly.musicdiary.ui.components.*
import com.fanketly.musicdiary.ui.theme.BlackBackgroundColor
import com.fanketly.musicdiary.ui.theme.TextWhite
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.PagerState
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.launch

@OptIn(
    ExperimentalPagerApi::class, ExperimentalLifecycleComposeApi::class,
    ExperimentalMaterialApi::class, ExperimentalAnimationApi::class
)
@Composable
fun SheetLayout(
    viewModel: DiaryViewModel = hiltViewModel(),
    musicViewModel: MusicViewModel = hiltViewModel()
) {
    //随page改底部导航高亮item
    val state: PagerState = rememberPagerState()
    val selectedIndex = remember { mutableStateOf(0) }
    LaunchedEffect(key1 = state.currentPage) {
        selectedIndex.value = state.currentPage
    }
    LaunchedEffect(key1 = state.currentPageOffset, block = {
        if (selectedIndex.value == 2 && state.currentPageOffset >= 0.4f) {
//        Log.i(TAG, "state.currentPageOffset: ${state.currentPageOffset}")
            musicViewModel.hideSongDetail()
        } else if (selectedIndex.value == 2) {
            musicViewModel.showSongDetail()
        }
    })
//    HomeHorizontalPager(state, selectedIndex, viewModel, musicViewModel)
}

@OptIn(
    ExperimentalPagerApi::class, ExperimentalLifecycleComposeApi::class,
    ExperimentalMaterialApi::class, ExperimentalAnimationApi::class
)
@Composable
fun HomeHorizontalPager(
//    state: PagerState,
//    selectedIndex: MutableState<Int>,
    viewModel: DiaryViewModel = hiltViewModel(),
    musicViewModel: MusicViewModel = hiltViewModel()
) {
    val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    if (uiState is DiaryUiState.UnKnown) return
    val context = LocalContext.current
//    val density = LocalDensity.current
//    val localView = LocalView.current
    //FOR HANDLING TIME CONSUMING TASKS
    val coroutineScope = rememberCoroutineScope()
    //日记数据
//    val diaryList = viewModel.getDiaries()
//    Log.i("TAG", "HomeHorizontalPager: ${diaryList.size}")

    /**
     *Page代码区
     **/
    //随page改底部导航高亮item
    val state: PagerState = rememberPagerState()
//    var selectedIndex by remember { mutableStateOf(0) }
    val selectedIndex = remember { mutableStateOf(0) }
    LaunchedEffect(key1 = state.currentPage) {
        selectedIndex.value = state.currentPage
    }
//    LaunchedEffect(key1 = state.currentPage, key2 = selectedIndex, block = {
//        selectedIndex = state.currentPage
//        if (state.currentPage != selectedIndex) state.animateScrollToPage(selectedIndex)
//    })
//    LaunchedEffect(key1 = selectedIndex, block = {
//        if (state.currentPage != selectedIndex) state.animateScrollToPage(selectedIndex)
//    })

    //如果在第三页偏移超过百分之40就隐藏底部音乐详情UI
    LaunchedEffect(key1 = selectedIndex.value, block = {
        Log.i(TAG, "state.currentPageOffset: ${state.currentPageOffset}")
        if (selectedIndex.value == 1 && state.currentPageOffset >= 0.4f) {
//        Log.i(TAG, "state.currentPageOffset: ${state.currentPageOffset}")
            musicViewModel.hideSongDetail()
        } else if (selectedIndex.value == 2) {
            musicViewModel.showSongDetail()
        }
    })


    /**拍照代码区**/
    var mCameraUri: Uri? = null
    val imagePath = remember {//Record the picture path
        mutableStateOf("")
    }
    //TakePicture calls the camera, saves the picture to the Uri specified by the developer after taking a picture, and returns true
    val openCameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture(),
        onResult = {
            if (it) {
                imagePath.value = FileUri.getPathByUri(mCameraUri) ?: ""
            }
        })

    /**文件选择代码区**/
    //for registration requests
    val openSelectPhotoLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = {
            it?.let {
                imagePath.value = FileUri.getPathByUri(it) ?: ""
            }
        })

    BackHandler() {
        if (sheetState.isVisible) {
            coroutineScope.launch {
                sheetState.hide()
            }
        } else {
            viewModel.dismissDiaryDetail()
        }
    }
    //Collects values from this StateFlow and represents its latest value via State in a lifecycle-aware manner.
    ModalBottomSheetLayout(sheetState = sheetState, sheetContent = {
        /**
         *底部弹窗Ui
         **/

        ChooseOrTakePhotoSheet(textColor = TextWhite, onChooseClick = {
            coroutineScope.launch {
                sheetState.hide()
            }
            //start file selection
            openSelectPhotoLauncher.launch("image/*")
        }, onTakeClick = {
            coroutineScope.launch {
                sheetState.hide()
            }
            //Build Uri of Save
            mCameraUri = context.contentResolver.insert(
                if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI else
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI, ContentValues()
            )
            //start taking pictures
            openCameraLauncher.launch(mCameraUri)
        })
    }) {
        AdaptScaffold(backgroundColor = BlackBackgroundColor,
            contentColor = BlackBackgroundColor,
            floatingActionButton = {
                /**
                 *底部浮动按钮Ui，根据不同状态显示的内容会改变
                 **/
                MusicImageAndProgress(
                    state.currentPage,
                    viewModel.checkToadyDiary(),    //今天是否已写日记
                    musicViewModel,
                    onClick = viewModel::showToadyDiaryDetail
                )

            },
            // floatingActionButton是否应该与bottomBar重叠半个高度
            isFloatingActionButtonDocked = true,
            floatingActionButtonPosition = FabPosition.End,
            bottomBar = {
                /**
                 *底部导航Ui
                 **/
                MyBottomNavigation(Modifier.navigationBarsPadding(), selectedIndex.value) {
                    //改变页数
                    coroutineScope.launch {
                        selectedIndex.value = it
                        state.animateScrollToPage(it)
                    }
                }
            },
            content = {
                HorizontalPager(
                    count = 3,
                    state = state,
                    modifier = Modifier
                        .statusBarsPadding()
                        .padding(it)
                ) { page ->
                    viewModel.updateDate()
                    when (page) {
                        0 -> DiaryCalendar(viewModel)//日历Ui
                        1 -> DiaryList(
                            viewModel.getDiaries(),
                            onClick = viewModel::showDiaryListDetail
                        )//日记列表Ui
                        2 -> MusicScaffold(musicViewModel)//音乐列表
                    }
                }
            })
        /**
         *日记详细信息，显示和退出缩放动画
         **/
        AnimatedVisibility(
            visible = viewModel.isShowDiaryDetail,
            enter = scaleIn(),
            exit = scaleOut()
        ) {
            viewModel.diaryDetailData?.let { model ->
                imagePath.value = model.imgPath
//                BackHandler(enabled = !sheetState.isVisible, onBack = viewModel::dismissDiaryDetail)
                DiaryDetail(
                    model, imagePath,
                    onUpdateClick = viewModel::update,
                    onImageClick = { coroutineScope.launch { sheetState.show() } },
                    onBackClick = viewModel::dismissDiaryDetail
                )
            }
        }
    }

}







